// Copyright (c) 2025, qiushike and contributors
// For license information, please see license.txt

frappe.ui.form.on("Initial Work Order", {
    onload: function(frm) {
		if (frm.doc.status == "Manufacture"){
			frm.set_read_only();
		}

        if (frm.is_new() && frm.doc.work_orders && frm.doc.work_orders.length===0){
            frm.add_child("work_orders");
        }

        if (frm.is_new()){
            frappe.db.get_value("Employee", {"user_id": frappe.session.user},
				"name",
				(r) => {
                    r && frm.set_value("employee", r.name);
                }
			);
        }
        
		frm.set_query('work_order', "work_orders", function(){
			return {
				filters: 
					{
						'status': ["in", ["Not Started", "In Process"]],
						'docstatus': ['<', 2],
						'company': frm.doc.company
					}
			}
		});
        frm.set_query('work_order', "tracking_numbers", function(){
            let work_order_list = frm.doc.work_orders.map(r=>r.work_order);
			return {
				filters: {'name': ["in", work_order_list]}
			}
		});
        frm.set_query("batch_no", "tracking_numbers", () => {
			return {
				query: "light_mes.queries.get_initial_work_order_batch_no",
                filters: {
					initial_work_order: frm.docname,
				}
			};
		});
	},
	refresh: function(frm) {
        if (frm.doc.work_orders && frm.doc.work_orders.length && frm.doc.work_orders[0].work_order){		
            frappe.db.get_value('Stock Entry', 
                {
                    "initial_work_order": frm.docname,
                    "purpose": "Material Transfer"
                },
                'name'
            )
            .then((r) => {                
                let is_return = $.isEmptyObject(r.message)? 0:1;
                let button = is_return? "Create Return Material Transfer":"Create Material Transfer"
                frm.add_custom_button(__(button), () => {
                    frappe.call({
                        method: 'light_mes.light_mes.doctype.initial_work_order.initial_work_order.create_stock_entry',
                        args: {
                            docname: frm.docname,
                            purpose: "Material Transfer",
                            is_return: is_return
                        },
                        freeze: true,
                        freeze_message: __("物料调拨创建中..."),
                    })
                    .then( (r) =>{
                        if (!r.exe && r.message) {
                            frm.reload_doc();	//py改了状态字段，需重新加载
                            var doc = frappe.model.sync(r.message)[0];
                            frappe.set_route("Form", r.message.doctype, doc.name);								
                        }
                    })
                });            
            });
        }
	}
})

frappe.ui.form.on("Initial Work Order Tracking Number", {
    print_tracking_number: function(frm, cdt, cdn){
        // 根据工序不同，需打印分条卷或拼卷标签
        let row = locals[cdt][cdn];
        let names = Array(row.label_qty | 1).fill(row.tracking_number);
        const doctype = "Tracking Number";
        names=JSON.stringify(names);
        const print_format = "追踪号标签";
        const pdf_options = JSON.stringify({
            "page-height": "82mm",
            "page-width": "60mm",
        });
        const w = window.open(
            "/api/method/frappe.utils.print_format.download_multi_pdf?" +
                "doctype=" +
                encodeURIComponent(doctype) +
                "&name=" +
                encodeURIComponent(names) +
                "&format=" +
                encodeURIComponent(print_format) +
                "&no_letterhead=1" +
                //(with_letterhead ? "0" : "1") +
                "&letterhead=" +
                encodeURIComponent("") +
                "&options=" +
                encodeURIComponent(pdf_options)
        );

        if (!w) {
            frappe.msgprint(__("Please enable pop-ups"));
        }
    }
})	